package com.yanqu.road.server.agent.inter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.connect.ServerLinkControl;
import com.yanqu.road.dao.impl.player.GrandChildDataDaoImpl;
import com.yanqu.road.entity.banquet.invitation.BanquetCrossInvitation;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.estatewar.UserEstateFloor;
import com.yanqu.road.entity.estatewar.UserEstateWarData;
import com.yanqu.road.entity.grandchild.GrandChildData;
import com.yanqu.road.entity.log.LogVipExp;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.player.UserPowerChildBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.JinLiProto;
import com.yanqu.road.pb.common.CommonProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.agent.AgentInterfaceMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.assistant.AssistantSkinModule;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.gameplayer.module.skin.SkinModule;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.manger.MammonConfigMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.config.SkinMgr;
import com.yanqu.road.server.manger.config.VehicleMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.messagesubscribe.MessageSubscribeMgr;
import com.yanqu.road.server.manger.player.DestroyRoleMgr;
import com.yanqu.road.server.manger.player.EstateWarMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.thirdparty.PlatformMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.cross.CrossUnionHonorsMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.pack.PackageHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AgentPlayer {

    /**
     * 修改用户头衔
     * @param param
     * @return
     */
    public String changeTitle(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] userIds = param.getString("userID").split(",");
        int title = param.getInteger("title");
        for (int i = 0; i < userIds.length; i++) {
            long userId = Long.parseLong(userIds[i]);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (player != null) {
                player.getUserInfo().setTitleId(title);
                player.getModule(PlayerModule.class).onTitleChange();
                player.getModule(PlayerModule.class).onUserInfoChange();
                PlayerProto.TitleUpgradeRespMsg.Builder respMsg = PlayerProto.TitleUpgradeRespMsg.newBuilder();
                respMsg.setRet(0);
                respMsg.setTitleId(player.getTitleId());
                player.sendPacket(Protocol.U_TITLE_UPGRADE, respMsg);
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    /**
     * 修改用户昵称
     * @param param
     * @return
     */
    public String changeNickName(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] userIds = param.getString("userID").split(",");
        String nickName = param.getString("nickName");
        int r = eAgentErrorCode.Success.getValue();
        for (int i = 0; i < userIds.length; i++) {
            long userId = Long.parseLong(userIds[i]);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (player != null) {
                if (PlatformMgr.changeNickName(player, nickName, false, false) != 0) {
                    r = eAgentErrorCode.NickNameError.getValue();
                }
            } else {
                UserBussiness.updateNickName(userId, nickName);
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, r);
        return ret.toString();
    }


    /**
     * 查看玩家在线情况
     * @param param
     * @return
     */
    public String onlineUser(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] playerIds = param.getString("userID").split(",");
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        AgentInterfaceMgr.setData(ret,online(playerIds));
        return ret.toString();
    }

    private String online(String[] playerIds){
        Map<String,Integer> userStateMap = new HashMap<>();
        for(String userIdStr : playerIds){
            long userId = Long.valueOf(userIdStr);
            GamePlayer user = GamePlayerMgr.getOnlinePlayer(userId);
            if(user != null && user.getState() == PlayerState.ONLINE){
                Long pingTime = user.getLastPingTime();
                Long nowTime = System.currentTimeMillis();
                if(nowTime - pingTime < 60*1000){
                    userStateMap.put(userIdStr,1);
                    continue;
                }
            }
            userStateMap.put(userIdStr,0);
        }

        return JSON.toJSONString(userStateMap);
    }

    public String kickOutPlayer(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] userIds = param.getString("userID").split(",");
        killPlayer(userIds);
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public static void killPlayer(String[] userIds) {
        for (String userId : userIds) {
            executeKillPlayer(Long.parseLong(userId));
        }
    }

    public static void executeKillPlayer(long userId){
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            onlinePlayer.sendPacket(ClientProtocol.U_ADMIN_KICK_OUT, CommonProto.NullValueMsg.newBuilder());
            try {
                Thread.sleep(50);
            }catch (Exception e){

            }
        }

        YanQuMessage castleReq = new YanQuMessage(Protocol.A_KICK_OUT_PLAYER);
        castleReq.setPlayerId(userId);
        ServerLinkControl.send(userId, castleReq);
    }

    public static String addVipExp(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] userIds = param.getString("userID").split(",");
        int money = param.getInteger("money");
        for (int i = 0; i < userIds.length; i++) {
            long userId = Long.parseLong(userIds[i]);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (player != null) {
                long originalValue = player.getUserInfo().getVipExp();
                player.getModule(RechargeModule.class).addVipExp(money);
                AutoLogMgr.add(new LogVipExp(player.getUserId(), originalValue, money, originalValue + money, 1, "后台虚拟充值"));//后台虚拟充值
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public static String addPrivilegeCard(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] playerIds = param.getString("userID").split(",");
        String type =  param.getString("type");
        int cardType;
        switch (type){
            case "week":
                cardType = eCardType.MonthCard.getValue();
                break;
            case "life":
                cardType = eCardType.YearCard.getValue();
                break;
            default:
                AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
                return ret.toString();
        }
        int mallId = 0;
        if(eCardType.MonthCard.getValue() == cardType){
            mallId = GameConfig.WEEK_CARD_MALL_ID;
        }else if(eCardType.YearCard.getValue() == cardType){
            mallId = GameConfig.LIFE_CARD_MALL_ID;
        }
        for (int i = 0; i < playerIds.length; i++) {
            long userId = Long.parseLong(playerIds[i]);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if(null != player){
                player.getModule(CardModule.class).addCard(cardType, true, mallId, null);
            }else{
                AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ErrorPlayer.getValue());
                return ret.toString();
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    private static boolean checkCBInv(List<String> invStrList){
        for (String invStr : invStrList){
            List<String> infoList = StringUtils.stringToStringList(invStr,"=");
            int type = Integer.valueOf(infoList.get(0));
            int num = Integer.valueOf(infoList.get(1));
            String serverListStr= infoList.get(2);
            if(type != eBanquetInvitationType.CrossBanquet1Invitation.getValue() &&
                    type != eBanquetInvitationType.CrossBanquet2Invitation.getValue() &&
                    type != eBanquetInvitationType.CrossBanquet3Invitation.getValue()){
               return false;
            }
            if(StringUtils.isNullOrEmpty(serverListStr)){
                return false;
            }
            List<Long> serverList = StringUtils.stringToLongList(serverListStr,",");
            if(!ServerListMgr.isServerIdIn(GameServer.getInstance().getServerId(),serverList)){
                return false;
            }
            if(num <= 0){
                return false;
            }
        }
        return true;
    }

    //道具列表&玩家列表&商会&活动id&排名&活动大类型&活动小类型&区服,区服|道具列表&玩家列表&商会&活动id&排名&活动大类型&活动小类型&区服,区服
    //info为101046=1;101047=2&101000280007174&666-b5b60bcb-5ea1-4a68-af1d-deed18c8f40e&10086&1&27&1&88881,88882|
    public static String addHonourItem(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] infoList = param.getString("info").split("\\|");
        for(String info : infoList){
            try {
                String[] paramList = info.split("&");
                String[] itemIds = paramList[0].split(";");
                String[] playerIds = paramList[1].split(",");
                String unionId = paramList[2];
                if(StringUtils.isNullOrEmpty(unionId) || playerIds.length < 1){
                    AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
                    return ret.toString();
                }
                for (String itemIdStr : itemIds){
                    String[] itemInfoList = itemIdStr.split("=");
                    int itemId = Integer.valueOf(itemInfoList[0]);
                    int num = Integer.valueOf(itemInfoList[1]);
                    GoodsInfo goodsInfo = GoodsMgr.getGoodsById(itemId);
                    if(goodsInfo == null || num == 0 || !GoodsMgr.isHonorScore(itemId)){
                        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
                        return ret.toString();
                    }
                }
            }catch (Exception e){
                AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
                return ret.toString();
            }
        }
        for(String info : infoList){
            String[] paramList = info.split("&");
            String[] itemIds = paramList[0].split(";");
            String[] playerIds = paramList[1].split(",");
            String unionId = paramList[2];
            String activityId = paramList[3];
            String rank = paramList[4];
            String acType = paramList[5];
            String acChildType = paramList[6];
            String[] serverIdStrList = paramList[7].split(",");
            List<Long> serverIdList = new ArrayList<>();
            for(String serverIdStr : serverIdStrList){
                serverIdList.add(Long.valueOf(serverIdStr));
            }
            for (String itemIdStr : itemIds){
                String[] itemInfoList = itemIdStr.split("=");
                int itemId = Integer.valueOf(itemInfoList[0]);
                int num = Integer.valueOf(itemInfoList[1]);
                for(String userIdStr : playerIds){
                    long userId = Long.valueOf(userIdStr);
                    //单独加道具用这个加，但是要记录的要用下面那个
//                    CrossUnionMgr.addRewardHonourItem(userId,unionId,itemId,num,eLogMoneyType.GmSend.getValue(),1);
                    CrossUnionHonorsMgr.addHonorsItemRecord(
                            Integer.valueOf(activityId),
                            Integer.valueOf(acType),
                            Integer.valueOf(acChildType),
                            Integer.valueOf(rank),
                            userId,
                            unionId,
                            num,
                            serverIdList,
                            itemId
                    );
                }
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    //发放跨服请帖
    public static String addCrossBanquetInvitation(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] playerIds = param.getString("userId").split(",");
        String infoStr =  param.getString("info");
        if(StringUtils.isNullOrEmpty(infoStr)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        List<String> invStrList = StringUtils.stringToStringList(infoStr,";");
        if(!checkCBInv(invStrList)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        for (String invStr : invStrList){
            List<String> infoList = StringUtils.stringToStringList(invStr,"=");
            int type = Integer.valueOf(infoList.get(0));
            int num = Integer.valueOf(infoList.get(1));
            String serverListStr= infoList.get(2);
            BanquetCrossInvitation inv = new BanquetCrossInvitation();
            inv.setServerIdsStr(serverListStr);
            for (int i = 0; i < playerIds.length; i++) {
                long userId = Long.parseLong(playerIds[i]);
                GamePlayer player = GamePlayerMgr.getPlayer(userId);
                if(null != player){
                    for(int j=0;j<num;j++){
                        player.getModule(BanquetModule.class).makeInvitation(type, JSON.toJSONString(inv));
                    }
                }
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }


    public static String rechargeShop(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<Long> playerIds = StringUtils.stringToLongList(param.getString("userIds"),",");
        List<Integer> mallIds = StringUtils.stringToIntegerList(param.getString("mallIds"),",");
        List<Integer> nums = StringUtils.stringToIntegerList(param.getString("muns"),",");
        if(mallIds.size() != nums.size()){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        if(RechargeModule.adminRechagetCheck(mallIds) != 0){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        for (int i = 0; i < playerIds.size(); i++) {
            long userId = playerIds.get(i);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if(player!=null){
                for(int j=0;j<mallIds.size();j++){
                    int mallId = mallIds.get(j);
                    int num = nums.get(j);
                    player.getModule(RechargeModule.class).adminRecharge(mallId,num);
                }
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

	public static String changePosition(JSONObject param){
		JSONObject ret = AgentInterfaceMgr.getDefaultRet();
		String[] playerIds = param.getString("userID").split(",");
		String city =  param.getString("city");
		String province = param.getString("province");
		for (int i = 0; i < playerIds.length; i++) {
			long userId = Long.parseLong(playerIds[i]);
			GamePlayer player = GamePlayerMgr.getPlayer(userId);
			if(player!=null){
				player.getModule(PlayerModule.class).setCity(city);
				if (!StringUtils.isNullOrEmpty(province)) {
                    player.getModule(PlayerModule.class).setProvince(province);
                }
			}
		}
		AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
		return ret.toString();
	}

    public static String setInstructor(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] playerIds = param.getString("userID").split(",");
        boolean isInstructor = param.getBoolean("isInstructor");
        for (int i = 0; i < playerIds.length; i++) {
            long userId = Long.parseLong(playerIds[i]);
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if(player!=null){
                player.getModule(PlayerModule.class).getUserInfo().setInstructor(isInstructor);
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    private static boolean checkCrossMammonDecoration(List<String> mammonStrList){
        for (String mammonStr : mammonStrList){
            List<String> infoList = StringUtils.stringToStringList(mammonStr,"=");
            int decorationId = Integer.valueOf(infoList.get(0));
            String serverListStr = infoList.get(1);
            if(!MammonConfigMgr.isCrossMammonDecorationId(decorationId)){ //不是跨服财神称号
                return false;
            }
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(decorationId);
            if(null == goodsInfo){//不存在道具信息
                return false;
            }
            if(goodsInfo.getParamList().get(3).intValue() <= 1){//道具信息配置不是跨服称号
                return false;
            }

            if(StringUtils.isNullOrEmpty(serverListStr)){
                return false;
            }
            List<Long> serverList = StringUtils.stringToLongList(serverListStr,",");
            if(!ServerListMgr.isServerIdIn(GameServer.getInstance().getServerId(),serverList)){
                return false;
            }
        }
        return true;
    }

    //发放跨服财神称号
    public static String addCrossMammonDecoration(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] playerIds = param.getString("userIds").split(",");
        String infoStr =  param.getString("info");
        if(StringUtils.isNullOrEmpty(infoStr)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        List<String> mammonStrList = StringUtils.stringToStringList(infoStr,";");
        if(!checkCrossMammonDecoration(mammonStrList)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        for (String mammonStr : mammonStrList){
            List<String> infoList = StringUtils.stringToStringList(mammonStr,"=");
            int decorationId = Integer.valueOf(infoList.get(0));
            String serverListStr = infoList.get(1);
            for (String playerId : playerIds) {
                long userId = Long.parseLong(playerId);
                GamePlayer player = GamePlayerMgr.getPlayer(userId);
                if (null != player) {
                    player.getModule(DecorationModule.class).consoleAddCrossMammonDecoration(decorationId, serverListStr);
                }
            }
        }

        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }


    public static String getPlayerModuleData(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String userIdStr = param.getString("userId");
        String module =  param.getString("module");
        if(StringUtils.isNullOrEmpty(module)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        long userId = Long.parseLong(userIdStr);
        GamePlayer player = GamePlayerMgr.getPlayer(userId);
        if (null != player) {
            List<String> moduleNameList = PackageHelper.getClassName("com.yanqu.road.server.gameplayer.module",true);
            for(String moduleName : moduleNameList){
                List<String> packageStrList = StringUtils.stringToStringList(moduleName,"\\.");
                if(packageStrList.get(packageStrList.size()-1).equals(module)){
                    try {
                        Class moduleClass = Class.forName(moduleName);
                        Object someModule = player.getModule(moduleClass);
//                        ret.put(module, JSON.toJSONString(someModule));
                        Field[] fields = someModule.getClass().getDeclaredFields();
                        Map<String,Object> infoMap = new ConcurrentHashMap<>();
                        for(Field field : fields){
                           if(!field.getName().equals("player") && !field.getName().equals("gamePlayer")){
                               field.setAccessible(true);
                               Object fieldObject = field.get(someModule);
                               infoMap.put(field.getName(), fieldObject);
                           }
                        }
                        ret.put(module,JSON.toJSONString(infoMap));
                    }catch (Exception e){
                        e.printStackTrace();
                        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
                        return ret.toString();
                    }
                }
            }
        }

        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    //扣除背包道具(可以扣除到负数的版本)
    public static String reduceUserBagCanNegative(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String userIdStr = param.getString("userId");
        String goodsParams =  param.getString("goodsParams");
        GamePlayer player = GamePlayerMgr.getPlayer(Long.valueOf(userIdStr));
        if (player == null){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.PlayerOffline.getValue());
            return ret.toString();
        }
        List<String> goodsList = StringUtils.stringToStringList(goodsParams,";");
        for(String stringInfo : goodsList){
            List<Integer> goodInfo = StringUtils.stringToIntegerList(stringInfo,"=");
            long l = player.getModule(BagModule.class).removeBagItemCanNegative(goodInfo.get(0), goodInfo.get(1), eLogMoneyType.BagBackendChange);
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }


    //背包道具变更,直接变更成传递过来的值
    public static String changeUserBag(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String userIdStr = param.getString("userId");
        String goodsParams =  param.getString("goodsParams");
        GamePlayer player = GamePlayerMgr.getPlayer(Long.valueOf(userIdStr));
        if (null != player){
            List<String> goodsList = StringUtils.stringToStringList(goodsParams,";");
            for(String stringInfo : goodsList){
                List<Integer> goodInfo = StringUtils.stringToIntegerList(stringInfo,"=");
                player.getModule(BagModule.class).changeBagItem(goodInfo.get(0),goodInfo.get(1),eLogMoneyType.BagBackendChange);
            }
        }else{
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.PlayerOffline.getValue());
            return ret.toString();
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    //背包道具变更,加上传递过来的值
    public static String valueChangeUserBag(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<Long> userIds = StringUtils.stringToLongList(param.getString("userIds"),",");
        int type = param.getInteger("type");
        String goodsParams =  param.getString("goodsParams");
        for(Long userId : userIds){
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (null != player){
                List<String> goodsList = StringUtils.stringToStringList(goodsParams,";");
                for(String stringInfo : goodsList){
                    List<Integer> goodInfo = StringUtils.stringToIntegerList(stringInfo,"=");
                    player.getModule(BagModule.class).addBagValueItem(goodInfo.get(0),goodInfo.get(1),type,eLogMoneyType.BagBackendChange);
                }
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    //后台修改玩家元宝数据
    public static String valueChangeIngot(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<Long> userIds = StringUtils.stringToLongList(param.getString("userIds"),",");
        long value = param.getLongValue("value");
        if(value > Integer.MAX_VALUE || value < Integer.MIN_VALUE){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        List<Long> killUserList = new ArrayList<>();
        if(!loadPlayer(userIds,killUserList)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ErrorPlayer.getValue());
            return ret.toString();
        }
        for(Long userId : userIds){
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (null != player){
                player.getModule(CurrencyModule.class).changeIngotsBackend(value,eLogMoneyType.GM,eLogMoneyType.GmSend);
            }
        }
        killPlayer(killUserList);
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }


    //后台修改玩家vip数据
    //type1修改vipExp,type2修改累计充值,type3修改每日充值
    public static String valueChangeVipExp(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<Long> userIds = StringUtils.stringToLongList(param.getString("userIds"),",");
        int value = param.getInteger("value");
        if(value > Integer.MAX_VALUE || value < Integer.MIN_VALUE){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        int type = param.getInteger("type");
        if(type != 1 && type != 2 && type != 3){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ArgumentError.getValue());
            return ret.toString();
        }
        List<Long> killUserList = new ArrayList<>();
        if(!loadPlayer(userIds,killUserList)){
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.ErrorPlayer.getValue());
            return ret.toString();
        }
        for(Long userId : userIds){
            GamePlayer player = GamePlayerMgr.getPlayer(userId);
            if (null != player){
                if(type == 1){
                    player.getModule(PlayerModule.class).changeVipExpBackend(value);
                }else if(type == 2){
                    player.getModule(PlayerModule.class).changeTotalRechargeBackend(value);
                }else if(type == 3){
                    player.getModule(PlayerModule.class).changeDayRechargeBackend(value);
                }
            }
        }
        killPlayer(killUserList);
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    //把不在内存中的用户加载到内存,然后标记要踢下线
    private static boolean loadPlayer(List<Long> userIds,List<Long> killUserList){
        for(Long userId : userIds){
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if(player == null){
                player = GamePlayerMgr.getPlayer(userId);
                killUserList.add(userId);
            }
            if(player == null){
                killPlayer(killUserList);
                return false;
            }
        }
        return true;
    }

    private static void killPlayer(List<Long> killUserList){
        //全部踢下线
        for(Long userId : killUserList){
            AgentPlayer.executeKillPlayer(userId);
        }
    }
    //测试微信发送消息
    public static String wechatSendMessage(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String wechatOpenId = param.getString("openId");
        MessageSubscribeMgr.testSend(wechatOpenId);
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public static String deleteUserRank(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String[] userIds = param.getString("userID").split(",");
        for (int i = 0; i < userIds.length; i++) {
            long userId = Long.parseLong(userIds[i]);
            UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
            GamePlayer player = new GamePlayer(userInfo);
            player.loadData();
            player.afterLoadData();
            if (player != null) {
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), userInfo.getUserId(), BigInteger.ZERO, eRankType.EarnSpeed.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.PatronsAbility.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), userId, BigInteger.ZERO, eRankType.TradeWarScore.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.BeautyIntimacy.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.HuntScore.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.Banquet.getValue(), "");

                UserPowerChild userPowerChild = UserPowerChildBussiness.getUserPowerChild(player.getUserId());
                userPowerChild.setChildEarnSpeed(BigInteger.ZERO);
                if (userPowerChild != null) {
                    RankMgr.changeChildRank(player.getUserId(), userPowerChild);
                }

                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.Charitable.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.ClinicValue.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.CreditValue.getValue(), player.getUserInfo().getHouseCreditLv() + "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.EmbroideryMeter.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.ManorProsperousValue.getValue(), "");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.WineShopPopularityValue.getValue(), "1");
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.FishPondScore.getValue(), "" + 1);

                Map<Integer, GrandChildData> grandChildProfessionTopMap = new GrandChildDataDaoImpl().getGrandChildProfessionTopMap(player.getUserId());
                GrandChildData tempGrandChild = null;
                if(null != grandChildProfessionTopMap) {
                    for (GrandChildData data : grandChildProfessionTopMap.values()) {
                        if(null == tempGrandChild){
                            tempGrandChild = data;
                        }else {
                            if(data.getEarnSpeed().compareTo(tempGrandChild.getEarnSpeed()) > 0){
                                tempGrandChild = data;
                            }
                        }
                    }
                }
                if (tempGrandChild != null) {
                    JSONObject dataObj = new JSONObject();
                    dataObj.put("id", tempGrandChild.getId());
                    dataObj.put("appearanceId", tempGrandChild.getAppearanceId());
                    dataObj.put("earnSpeed", tempGrandChild.getEarnSpeed());
                    RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.GrandChildEarnSpeed.getValue(), dataObj.toJSONString());
                }
                RankMgr.changeUserRank(eBigRankType.Normal.getValue(), player.getUserId(), BigInteger.ZERO, eRankType.AssistantDressOnValue.getValue(), player.getModule(AssistantSkinModule.class).getCollocationString());


                for (UserPatrons patrons : player.getModule(PatronsModule.class).getUserPatronsList()) {
                    SkinModule skinModule = player.getModule(SkinModule.class);
                    for (int skinId : SkinMgr.getSkinListByRoleId(eSkinType.Patrons, patrons.getPatronsId())) {
                        UserSkin userSkin = skinModule.getUserSkinMap().get(skinId);
                        if (userSkin != null) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("skillLevel", "1");
                            jsonObject.put("value", "0");
                            jsonObject.put("skinCombLv", "0");
                            jsonObject.put("skinCombSkillLv", "0");
                            RankMgr.changeUserRank(eBigRankType.Skin.getValue(), player.getUserId(), BigInteger.ONE, skinId, jsonObject.toJSONString());
                        }
                    }

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("patronsId", patrons.getPatronsId());
                    jsonObject.put("skinId", patrons.getSkinId());
                    jsonObject.put("promotionId", patrons.getShowPromotionId());
                    RankMgr.changeUserRank(eBigRankType.Patrons.getValue(), player.getUserId(),BigInteger.ZERO, 0, jsonObject.toJSONString());
                    RankMgr.changeUserRank(eBigRankType.Patrons.getValue(), player.getUserId(), BigInteger.ZERO, patrons.getPatronsId(), jsonObject.toJSONString());
                }

                for (Map.Entry<Integer, UserBeauty> beautyEntry : player.getModule(BeautyModule.class).getBeautyMap().entrySet()) {
                    UserBeauty userBeauty = beautyEntry.getValue();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", userBeauty.getBeautyId());
                    jsonObject.put("skinId", userBeauty.getSkinId());
                    jsonObject.put("lv", userBeauty.getIdentitySkillLv());
                    jsonObject.put("qua", userBeauty.getQuality());
                    RankMgr.changeUserRank(eBigRankType.Beauty.getValue(), player.getUserId(), BigInteger.ONE, eRankType.Beauty.getValue(), jsonObject.toJSONString());
                    RankMgr.changeUserRank(eBigRankType.Beauty.getValue(), player.getUserId(), BigInteger.ONE, userBeauty.getBeautyId(), jsonObject.toJSONString());
                }

                for (UserVehicle userVehicle : player.getModule(VehicleModule.class).getUserVehicleMap().values()) {
                    if (!VehicleMgr.canJoinRank(userVehicle.getTemplateId())) {
                        break;
                    }
                    // 技能
                    JSONArray skillArray = new JSONArray();
                    for (UserVehicleSkill skill : userVehicle.getSkillMapEffect().values()) {
                        JSONObject skillObject = new JSONObject();
                        skillObject.put("pos", skill.getSkillPos());
                        skillObject.put("type", skill.getSkillType());
                        skillObject.put("value", skill.getValue());
                        skillArray.add(skillObject);
                    }

                    // 光环技能
                    JSONArray otherSkillArray = VehicleMgr.getOtherSkillArray(userVehicle);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("qualification", VehicleMgr.getVehicleQualification(userVehicle.getTemplateId(), userVehicle.getLevel()));
                    jsonObject.put("addition", 0);
                    jsonObject.put("skillList", skillArray);
                    jsonObject.put("level", userVehicle.getLevel());
                    jsonObject.put("otherSkillList", otherSkillArray);

                    RankMgr.changeUserRank(eBigRankType.Vehicle.getValue(), player.getUserId(),
                            BigInteger.valueOf(Long.MIN_VALUE),
                            userVehicle.getTemplateId(), jsonObject.toJSONString());

                }

                //乔迁
                synchronized (EstateWarMgr.getLockObj()){
                    UserEstateWarData userEstateWarData = player.getModule(EstateWarModule.class).getUserEstateWarData();
                    if(null != userEstateWarData){
                        UserEstateFloor userEstateFloor = EstateWarMgr.getUserEstateFloor(userEstateWarData.getType(), userEstateWarData.getPos());
                        if (null != userEstateFloor && userEstateFloor.getUserId() == player.getUserId()) {
                            EstateWarMgr.clearEstateFloorUser(userEstateFloor);
                            userEstateWarData.setType(1);
                            userEstateWarData.setPos(1);
                            player.saveData();
                        }
                    }
                }
            }
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public String cancelDestroyRole(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<Long> userIds = StringUtils.stringToLongList(param.getString("userIds"),",");
        for(long userId : userIds){
            DestroyRoleMgr.cancelDestroyRole(userId);
        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    /**
     * 移除锦鲤
     */
    public static String removeJinLi(JSONObject param){
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        int activityId = param.getInteger("activityId");
        int mallId = param.getInteger("mallId");
        List<Long> userIdList = StringUtils.stringToLongList(param.getString("userId"), ",");
        JinLiProto.CrossRemoveJinLiReqMsg.Builder builder = JinLiProto.CrossRemoveJinLiReqMsg.newBuilder();
        builder.setActivityId(activityId);
        builder.setMallId(mallId);
        builder.addAllUserId(userIdList);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_JINLI_REMOVE, builder));
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

}
